package csc.daonjpa.java.controller;

import java.util.Date;
import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.service.BankService;

/**
 * This controller handles account related actions
 * 
 * @author nvu3
 * 
 */
@Controller
public class AccountController {
	private static final Logger LOG = Logger.getLogger(AccountController.class);
	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	/**
	 * Adds account to DB
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createAccount", method = RequestMethod.POST)
	public String addAccount(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String accountType = request.getParameter("accountType");
		String accountName = request.getParameter("accountName");
		String accountNumber = request.getParameter("accountNumber");
		long amount = Long.parseLong(request.getParameter("availableAmount"));
		Date now = new Date();

		// Check if there is an existing account with the accountNumber
		Account existAcc = bankService.getAccountByAccNumber(accountNumber);
		if (existAcc != null) {
			model.addAttribute(
					"errorMessage",
					"There has been an existing account with this account number! Please input another account number");
		} else {
			// Bi-directional
			Customer currentCustomer = (Customer) request.getSession()
					.getAttribute("currentCustomer");
			Account account = new Account(accountNumber, accountName,
					accountType, amount, now, now, currentCustomer);

			currentCustomer.addAccount(account);
			account.setCustomer(currentCustomer);

			try {
				// Save account to DB
				bankService.addAccount(account);
				model.addAttribute("successMessage",
						"Added new account successfully");
			} catch (PersistenceException ex) {
				if (ex.getCause() instanceof ConstraintViolationException) {
					model.addAttribute("errorMessage",
							"Duplicated account found");
				} else {
					model.addAttribute("errorMessage",
							"Error adding new account");
				}
				LOG.error("Error found adding an account", ex);
				throw ex;
			} catch (Exception e) {
				LOG.error("General Error found adding an account", e);
				throw e;
			}
		}
		return "forward:/listAccount";
	}

	@RequestMapping(value = "/listAccount")
	public ModelAndView getAccountList(HttpServletRequest request, Model model) {
		ModelAndView modelAndView = null;
		Customer customer = (Customer) request.getSession().getAttribute(
				"currentCustomer");
		if (customer != null) {
			// Get the customer loginid
			Customer currentCustomer = (Customer) request.getSession()
					.getAttribute("currentCustomer");
			String custLoginId = currentCustomer.getLoginid();

			// Get the list of all accounts from DB
			List<Account> accountList = bankService
					.getAccountsByCustomerId(custLoginId);

			modelAndView = new ModelAndView("accountList");
			modelAndView.addObject("listAccount", accountList);
		} else {
			modelAndView = new ModelAndView("home");
		}
		return modelAndView;
	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {

		ModelAndView model = new ModelAndView("accountList");
		model.addObject("errorMessage", "Exception occurred");

		return model;
	}
}
